package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONString;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDto;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.SIGN_MONTH_KEY;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource()
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result sendCode(String phone) {
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.不符合，返回错误信息
            return Result.fail("手机号错误!");
        }

        // 3.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 4.保存验证码到Redis
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone,
                code, RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        // 5.发送验证码
        log.debug("短信验证码：{}", code);

        // 6.返回
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        // 1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号错误!");
        }

        // 2.校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();
        if (cacheCode == null || !cacheCode.equals(code)) {
            return Result.fail("验证码错误!");
        }

        // 3.手机号查询用户
        User user = lambdaQuery().eq(User::getPhone, phone).one();
        if (user == null) {
            // 用户不存在，创建新用户
            user = createUserWithPhone(phone);
        }

        // 4.保存用户信息到Redis中
        String token = UUID.randomUUID().toString();
        UserDto userDto = BeanUtil.copyProperties(user, UserDto.class);
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        Map<String, Object> map = BeanUtil.beanToMap(userDto, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(tokenKey, map);
        stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.HOURS);
        return Result.ok(token);
    }

    /**
     * 用户签到
     *
     * @return null
     */
    @Override
    public Result sign() {
        // 获取当前用户
        UserDto user = UserHolder.getUser();
        // 获取当前日期
        LocalDate now = LocalDate.now();
        // key
        String key = SIGN_MONTH_KEY + user.getId() +
                now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        stringRedisTemplate.opsForValue()
                .setBit(key, now.getDayOfMonth() - 1, true);
        return Result.ok();
    }

    /**
     * 统计当前用户截止当前时间在本月内的连续签到天数
     *
     * @return 结果
     */
    @Override
    public Result signCount() {
        UserDto user = UserHolder.getUser();
        LocalDate now = LocalDate.now();
        String key = SIGN_MONTH_KEY + user.getId() +
                now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        // BITFIELD sign:1010:2024:03 GET u6 0
        List<Long> result = stringRedisTemplate.opsForValue()
                .bitField(key, BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(now.getDayOfMonth()))
                        .valueAt(0));
        if (result == null || result.isEmpty()) {
            return Result.fail("未签到");
        }
        Long num = result.get(0);
        // 循环遍历无符号十进制数，与 1 做与运算，得到每天的bit
        int count = 0;
        // 未签到天
        while ((num & 1) != 0) {
            count++;
            // 无符号右移
            num >>>= 1;
        }
        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
